// 全局变量
let selectedFiles = [];
let uploadInProgress = false;

// DOM 元素
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
const fileList = document.getElementById('fileList');
const filesContainer = document.getElementById('filesContainer');
const uploadProgress = document.getElementById('uploadProgress');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
const result = document.getElementById('result');
const siteUrl = document.getElementById('siteUrl');
const copyBtn = document.getElementById('copyBtn');
const customDomain = document.getElementById('customDomain');
const sitesContainer = document.getElementById('sitesContainer');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    loadSites();
});

// 拖拽上传
dropZone.addEventListener('click', () => fileInput.click());

dropZone.addEventListener('dragover', (e) => {
    e.preventDefault();
    dropZone.classList.add('dragover');
});

dropZone.addEventListener('dragleave', () => {
    dropZone.classList.remove('dragover');
});

dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    
    const files = Array.from(e.dataTransfer.files);
    handleFiles(files);
});

fileInput.addEventListener('change', (e) => {
    const files = Array.from(e.target.files);
    handleFiles(files);
});

// 处理文件
function handleFiles(files) {
    selectedFiles = files;
    displayFiles();
    uploadBtn.classList.remove('hidden');
}

// 显示文件列表
function displayFiles() {
    fileList.classList.remove('hidden');
    filesContainer.innerHTML = '';
    
    selectedFiles.forEach(file => {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item flex items-center justify-between p-3 bg-gray-50 rounded-md';
        fileItem.innerHTML = `
            <div class="flex items-center space-x-3">
                <i class="fas fa-file text-blue-500"></i>
                <div>
                    <p class="text-sm font-medium">${file.name}</p>
                    <p class="text-xs text-gray-500">${formatFileSize(file.size)}</p>
                </div>
            </div>
            <button onclick="removeFile(${selectedFiles.indexOf(file)})" 
                    class="text-red-500 hover:text-red-700">
                <i class="fas fa-times"></i>
            </button>
        `;
        filesContainer.appendChild(fileItem);
    });
}

// 移除文件
function removeFile(index) {
    selectedFiles.splice(index, 1);
    if (selectedFiles.length === 0) {
        fileList.classList.add('hidden');
        uploadBtn.classList.add('hidden');
    } else {
        displayFiles();
    }
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 上传文件
uploadBtn.addEventListener('click', uploadFiles);

async function uploadFiles() {
    if (uploadInProgress || selectedFiles.length === 0) return;
    
    uploadInProgress = true;
    uploadBtn.disabled = true;
    uploadProgress.classList.remove('hidden');
    
    const formData = new FormData();
    selectedFiles.forEach(file => {
        formData.append('files', file);
    });
    
    if (customDomain.value.trim()) {
        formData.append('siteId', customDomain.value.trim());
    }
    
    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });
        
        const data = await response.json();
        
        if (data.success) {
            siteUrl.value = data.url;
            result.classList.remove('hidden');
            uploadProgress.classList.add('hidden');
            
            // 清空选择
            selectedFiles = [];
            fileList.classList.add('hidden');
            uploadBtn.classList.add('hidden');
            customDomain.value = '';
            
            // 刷新站点列表
            loadSites();
        }
    } catch (error) {
        console.error('上传失败:', error);
        progressText.textContent = '上传失败，请重试';
        progressText.className = 'text-sm text-red-600 mt-2';
    } finally {
        uploadInProgress = false;
        uploadBtn.disabled = false;
    }
}

// 复制链接
copyBtn.addEventListener('click', () => {
    siteUrl.select();
    document.execCommand('copy');
    
    const originalText = copyBtn.innerHTML;
    copyBtn.innerHTML = '<i class="fas fa-check"></i>';
    setTimeout(() => {
        copyBtn.innerHTML = originalText;
    }, 2000);
});

// 加载站点列表
async function loadSites() {
    try {
        const response = await fetch('/sites');
        const sites = await response.json();
        
        if (sites.length === 0) {
            sitesContainer.innerHTML = '<p class="text-gray-500 text-center">暂无托管站点</p>';
            return;
        }
        
        sitesContainer.innerHTML = '';
        sites.forEach(site => {
            const siteItem = document.createElement('div');
            siteItem.className = 'flex items-center justify-between p-3 bg-gray-50 rounded-md';
            siteItem.innerHTML = `
                <div>
                    <p class="font-medium">${site.customDomain || site.id}</p>
                    <a href="${site.url}" target="_blank" class="text-sm text-blue-500 hover:underline">
                        ${site.url}
                    </a>
                </div>
                <div class="flex space-x-2">
                    <button onclick="copyUrl('${site.url}')" 
                            class="text-gray-500 hover:text-gray-700">
                        <i class="fas fa-copy"></i>
                    </button>
                    <button onclick="deleteSite('${site.id}')" 
                            class="text-red-500 hover:text-red-700">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            sitesContainer.appendChild(siteItem);
        });
    } catch (error) {
        console.error('加载站点失败:', error);
    }
}

// 复制URL
function copyUrl(url) {
    navigator.clipboard.writeText(url);
}

// 删除站点
async function deleteSite(siteId) {
    if (!confirm('确定要删除这个站点吗？')) return;
    
    try {
        const response = await fetch(`/sites/${siteId}`, {
            method: 'DELETE'
        });
        
        const data = await response.json();
        if (data.success) {
            loadSites();
        }
    } catch (error) {
        console.error('删除失败:', error);
    }
}
